package com.magic.smartcity.view.more.hospital

import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.widget.doOnTextChanged
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.Navigation
import com.magic.smartcity.R
import com.magic.smartcity.beans.HospitalPatientCard
import com.magic.smartcity.databinding.FragmentHospitalPatientCardEditBinding
import com.magic.smartcity.view.more.viewmodels.HospitalViewModel

class HospitalPatientCardEditFragment : Fragment() {
    private lateinit var binding: FragmentHospitalPatientCardEditBinding
    private val model by lazy {
        ViewModelProvider(this).get(HospitalViewModel::class.java)
    }
    private lateinit var patientCard: HospitalPatientCard
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        patientCard = arguments?.getSerializable("patientCardDetail")!! as HospitalPatientCard
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentHospitalPatientCardEditBinding.inflate(layoutInflater)

        initView()

        return binding.root
    }

    private fun initView() {
        //性别单选按钮设置数据改动
        binding.sexGroup.setOnCheckedChangeListener { _, _ ->
            patientCard.sex = if (binding.nan.isChecked) "0" else "1"
        }

        binding.patientDetail = patientCard
        if (patientCard.sex.equals("0")) binding.nan.isChecked = true
        else binding.nv.isChecked = true
        binding.submitEdit.setOnClickListener {
            //检查是否存在空输入
            when {
                binding.name.text.toString().isEmpty() -> {
                    binding.name.error = "请输入姓名"
                }
                binding.idCard.text.toString().isEmpty() -> {
                    binding.idCard.error = "请输入身份证号"
                }
                binding.phonenumber.text.toString().isEmpty() -> {
                    binding.phonenumber.error = "请输入手机号"
                }
                binding.address.text.toString().isEmpty() -> {
                    binding.address.error = "请输入地址"
                }
                binding.birthday.text.toString().isEmpty() -> {
                    binding.birthday.error = "请输入生日日期"
                }
                //没有存在空输入，检查输入格式
                else -> {
                    model.editHospitalPatientCard(patientCard)//请求修改
                    //监视是否修改成功
                    model.editHospitalPatientCardOk.observe(viewLifecycleOwner){
                        Toast.makeText(context, "修改成功", Toast.LENGTH_SHORT).show()
                        Navigation.findNavController(binding.root).popBackStack()
                    }

                }
            }
        }
    }

}